import { defineStore } from 'pinia'
import { DARK_THEME, THEME_KEY, PRIMARY_COLOR_KEY } from '@/const/theme'
import { GLOBAL_CONFIG } from '@/const/storage'
import { isMobileDev } from '@/utils/regexp'
import { getStorage, setStorage } from '@/app/storage'
import {
  changePrimaryColor,
  changeThemeTransition,
  changeWeakOrGreyMode,
  changeAsideStyle,
} from '@/app/style'
import { CONFIG_STORE_NAME, LAYOUTS, DefaultConfig } from '../const'

export default defineStore(CONFIG_STORE_NAME, () => {
  const globalConfig = ref(getStorage(GLOBAL_CONFIG) || DefaultConfig)
  const isMobile = ref(isMobileDev())

  const isDark = computed(() => globalConfig.value.theme === DARK_THEME)

  function setConfig(key, value, event) {
    globalConfig.value[key] = value
    setStorage(GLOBAL_CONFIG, globalConfig.value)

    const handlers = {
      isBlur: () => addBlurClass(value),
      isWeakMode: () => changeWeakOrGreyMode('weak', value),
      isGreyMode: () => changeWeakOrGreyMode('grey', value),
      isDarkAside: () => changeAsideStyle(value),
      [PRIMARY_COLOR_KEY]: () => changePrimaryColor(value),
      [THEME_KEY]: () => changeThemeTransition(event, value),
    }
    handlers[key] && handlers[key]()
  }

  function resetConfig(event) {
    setStorage(GLOBAL_CONFIG, DefaultConfig)
    changePrimaryColor(DefaultConfig.primaryColor)
    globalConfig.value.theme === DARK_THEME &&
      changeThemeTransition(event, DefaultConfig.theme)
    globalConfig.value = DefaultConfig
  }

  function setIsMobile(val) {
    isMobile.value = val
  }

  function changeLayoutHorizontalStyle(value) {
    if (value === LAYOUTS.Horizontal) {
      document.documentElement.style.setProperty(
        '--el-menu-horizontal-sub-item-height',
        '46px',
      )
    }
  }

  // el-overlay添加blur样式
  function addBlurClass(isBlur) {
    const elements = document.querySelectorAll('.el-overlay')
    elements.forEach((el) => {
      isBlur
        ? el.classList.add('blur-overlay')
        : el.classList.remove('blur-overlay')
    })
  }

  return {
    globalConfig,
    isMobile,
    isDark,
    DefaultConfig,
    setConfig,
    resetConfig,
    setIsMobile,
    addBlurClass,
    changeLayoutHorizontalStyle,
  }
})
